from os import system, popen
from time import sleep
import re


# tolerate maximal interval time of process "crawler.py" execute per frequency,unit is MINUTE
interval = 5
# the interval of this program starting check
sleepMin = 1

# shell command
ps_cmd = "ps -ef | grep " + "\"" + "crawler\.py" + "\""
sysMin_cmd = 'date +%M' # get the minute from current system time
sysHou_cmd = 'date +%H' # get the hour from current system time
pid_cmd = "pgrep " + "\"" + "crawler\.py" + "\""
kill_cmd = "kill "

def main():

    while True:
        # get the system current minute
        curMin = popen(sysMin_cmd).read()
        curHou = popen(sysHou_cmd).read().strip("\n")
        print("check time: %s" %(popen("date +%H:%M,%D").read()))

        # get the process id
        proId = popen(pid_cmd).read()

        # get the current running process start time
        processCont = popen(ps_cmd).read()
        cont = processCont.split("\n")
        for subcont in cont:
            if re.search(r'/python', subcont) is not None:
                print("%s --> [target]" %subcont)
                targetTIme = subcont
                break
            else:
                print(subcont)
        time = re.search(r'\d\d:\d\d', targetTIme)   # get the entire time including hour and minute
        staMin = targetTIme[time.start()+3: time.end()] # get the minute where target process start from above result
        staHou = targetTIme[time.start(): time.end()+2]
        print("process ID which need to be checked: %s" %proId)
        print( "start minute: %s:%s" %(staHou, staMin) )
        print( "start minute: %s:%s" %(curHou, curMin) )

        # if the process execute exceed the tolerated interval
        if int(curHou) == int(staHou): # within same hour
            if int(curMin) - int(staMin) >= interval:
                print("process running time EXCEED %s minute, KILL it!" %interval)
                system(kill_cmd + proId)
        else:   # within different hour
            if ( (60-int(staMin)) + int(curMin) ) >= interval: # get the ABSOLUTE value of difference
                print("process running time EXCEED %s minute, KILL it!" % interval)
                system(kill_cmd + proId)

        print(">>>>>>>>>>>\n")
        # sleep whatever happen :)
        sleep(sleepMin * 60)

if __name__ == '__main__':
    main()
